import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import { DeviceService } from '../../../share/device.service';
import { Subscription } from 'rxjs/Rx';
import { Device } from '../../../classes/Device';

@Component({
  selector: 'app-content-header',
  templateUrl: './content-header.component.html',
  styleUrls: ['./content-header.component.css']
})
export class ContentHeaderComponent implements OnInit, AfterViewInit, OnDestroy {

  // 定义订阅流对象
  public subscription: Subscription;
  public deviceInfo: Device;
// 耗电量
  public powerConsumption: number;
// 从服务中初始化设备信息
  constructor(public deviceService: DeviceService) { }
  ngOnInit() {
    this.deviceInfo = this.deviceService.getDeviceInfo();
    this.powerConsumption = Math.round(Math.random() * 1000);
  }

// 初始化完组件视图及其子视图之后启动订阅
  ngAfterViewInit(): void {
     this.subscription = this.deviceService.getMessage().subscribe(msg => {
       this.deviceInfo = msg;
     })
  }

// 组件销毁之前销毁取消订阅
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }


}
